package com.example.user.interceptor;

import com.example.user.exception.TokenIsWrongException;
import com.example.user.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 *
 * @author tong
 * @date 2023/03/13
 */
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 先获取请求头里的token
        String token = request.getHeader("token");
        // token判空
        if (StringUtils.isEmpty(token)) {
            System.out.println("这次的请求是：" + request.getServletPath());
            throw new RuntimeException("未登录，请登录后重试!");
        }
        // token解析是否成功，若成功，则放行；否则，不放行
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();
            System.out.println("sub:" + subject);
        } catch (Exception e) {
            throw new TokenIsWrongException("token解析错误，请稍后重试!");
        }
        // 返回值代表是否放行
        return true;
    }
}
